package com.kuang;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageOp;
import java.awt.image.ImageObserver;
import java.awt.image.RenderedImage;
import java.awt.image.renderable.RenderableImage;
import java.io.IOException;
import java.text.AttributedCharacterIterator;
import java.util.Map;
import java.util.Random;

public class ImageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        super.doGet(req, resp);
//        浏览器设置3s刷新
        resp.setHeader("refresh","3");
//        在内存中创建一张图片
        BufferedImage images = new BufferedImage(80,20,BufferedImage.TYPE_INT_RGB);
//        得到图片
        Graphics2D g=(Graphics2D) images.getGraphics();
//        设置图片的背景颜色
        g.setColor(Color.white);
        g.fillRect(0,0,80,20);
//        给图片写数据
        g.setColor(Color.blue);
        g.setFont(new Font(null,Font.BOLD,20));
        g.drawString(makeNum(),0,20);
//        告诉浏览器，这个请求用图片的方式打开
//        image/jepg 图片下载  image/webp窗口打开3秒刷新
        resp.setContentType("image/webp");
//        告诉浏览器不要设置缓存
        resp.setHeader("Cache-Control", "no-cache"); // HTTP 1.1
        resp.setHeader("Pragma", "no-cache"); // HTTP 1.0
        resp.setDateHeader("Expires", -1); // 过去的时间，表示响应已经过期
//        把图片写给浏览器
        ImageIO.write(images,"jpg",resp.getOutputStream());
    }
    public String makeNum(){
        Random random=new Random();
        String num = random.nextInt(999999)+"";
        StringBuffer stringBuffer = new StringBuffer();
        for(int i=0;i<7-num.length();i++){
            stringBuffer.append("0");
        }
        return stringBuffer.toString()+num;
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
